package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.base.mapper.DictDataMapper;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementQuery;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class StatementServiceImpl implements IStatementService {

    @Autowired
    private StatementMapper statementMapper;

    @Autowired
    private DictDataMapper dictDataMapper;

    @Autowired
    private StatementItemMapper statementItemMapper;


    @Override
    public TablePageInfo<Statement> query(StatementQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<Statement>(statementMapper.selectForList(qo));
    }


    @Override
    public void save(Statement statement) {
        // 设置新建时间
        statement.setCreateTime(new Date());

        // 设置默认值
        statement.setStatus(Statement.STATUS_CONSUME);
        statement.setTotalAmount(new BigDecimal("0"));
        statement.setTotalQuantity(new BigDecimal("0"));
        statement.setDiscountAmount(new BigDecimal("0"));

        // 新增操作
        statementMapper.insert(statement);
    }

    @Override
    public Statement get(Long id) {
        return statementMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(Statement statement) {
        Statement dbItem = this.get(statement.getId());
        // 消费中状态才可以编辑
        if (Statement.STATUS_PAID.equals(dbItem.getStatus())) {
            throw new BusinessException("非法操作");
        }

        // 设置默认值
        statement.setStatus(Statement.STATUS_CONSUME);

        // 修改操作
        statementMapper.updateByPrimaryKey(statement);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            Statement statement = this.get(dictId);
            // 消费中状态才可以删除
            if (Statement.STATUS_PAID.equals(statement.getStatus())) {
                throw new BusinessException("非法操作");
            }

            // 删除服务结算单-服务单项 关系表数据
            statementMapper.deleteRelation(dictId);
            statementMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<Statement> list() {
        return statementMapper.selectAll();
    }

    @Override
    public void pay(Long statementId) {
        Statement statement = this.get(statementId);
        // 非消费中状态不可支付
        if (!Statement.STATUS_CONSUME.equals(statement.getStatus())) {
            throw new BusinessException("非法操作");
        }

        // 获取操作者的id
        Long id = ShiroUtils.getUser().getId();

        // 修改结算单 状态、支付时间、收款人id
        statementMapper.payStatus(statementId,Statement.STATUS_PAID,id);
    }

    @Override
    public Workbook exportStatement(Long statementId) {
        Workbook workbook = new XSSFWorkbook();

        // 服务结算单sheet
        Sheet sheet1 = workbook.createSheet("结算单");
        Row row0 = sheet1.createRow(0);
        row0.createCell(0).setCellValue("客户姓名");
        row0.createCell(1).setCellValue("客户电话");
        row0.createCell(2).setCellValue("到店时间");
        row0.createCell(3).setCellValue("车牌号码");
        row0.createCell(4).setCellValue("汽车类型");
        row0.createCell(5).setCellValue("服务类型");
        row0.createCell(6).setCellValue("是否预约订单");
        row0.createCell(7).setCellValue("消费状态");
        row0.createCell(8).setCellValue("支付时间");
        row0.createCell(9).setCellValue("总订单金额");
        row0.createCell(10).setCellValue("服务项数量");
        row0.createCell(11).setCellValue("优惠金额");
        row0.createCell(12).setCellValue("实付金额");
        row0.createCell(13).setCellValue("预约时间");
        row0.createCell(14).setCellValue("备注信息");

        Statement statement = statementMapper.selectByPrimaryKey(statementId);
        Row row1 = sheet1.createRow(1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        row1.createCell(0).setCellValue(statement.getCustomerName());
        row1.createCell(1).setCellValue(statement.getCustomerPhone());
        if (statement.getActualArrivalTime() != null) {
            row1.createCell(2).setCellValue(dateFormat.format(statement.getActualArrivalTime()));
        }
        row1.createCell(3).setCellValue(statement.getLicensePlate());
        row1.createCell(4).setCellValue(statement.getCarSeries());
        row1.createCell(5).setCellValue(dictDataMapper.selectDictLabel("si_service_catalog",statement.getServiceType().toString()).getLabel());
        row1.createCell(6).setCellValue(statement.getAppointmentId() == null?"否":"是");
        row1.createCell(7).setCellValue(dictDataMapper.selectDictLabel("statement_status",statement.getStatus().toString()).getLabel());
        if (statement.getPayTime() != null) {
            row1.createCell(8).setCellValue(dateFormat.format(statement.getPayTime()));
        }
        row1.createCell(9).setCellValue(statement.getTotalAmount().doubleValue());
        row1.createCell(10).setCellValue(statement.getTotalQuantity().intValue());
        row1.createCell(11).setCellValue(statement.getDiscountAmount().doubleValue());
        row1.createCell(12).setCellValue(statement.getTotalAmount().subtract(statement.getDiscountAmount()).doubleValue());
        if (statement.getCreateTime() != null) {
            row1.createCell(13).setCellValue(dateFormat.format(statement.getCreateTime()));
        }
        row1.createCell(14).setCellValue(statement.getInfo());

        // 服务项明细sheet
        Sheet sheet2 = workbook.createSheet("服务项明细");
        Row row00 = sheet2.createRow(0);
        row00.createCell(0).setCellValue("服务项名称");
        row00.createCell(1).setCellValue("服务项价格");
        row00.createCell(2).setCellValue("购买数量");
        row00.createCell(3).setCellValue("合计");
        List<StatementItem> list = statementItemMapper.selectByStatementId(statementId);
        for (int i = 0; i < list.size(); i++) {
            Row row = sheet2.createRow(i + 1);
            row.createCell(0).setCellValue(list.get(i).getItemName());
            row.createCell(1).setCellValue(list.get(i).getItemPrice().doubleValue());
            row.createCell(2).setCellValue(list.get(i).getItemQuantity());
            row.createCell(3).setCellValue(list.get(i).getItemPrice().multiply(new BigDecimal(list.get(i).getItemQuantity().toString()).setScale(2, RoundingMode.HALF_UP)).doubleValue());
        }
        Row rowTotal = sheet2.createRow(list.size() + 1);
        rowTotal.createCell(3).setCellValue(statement.getTotalAmount().doubleValue());

        return workbook;
    }
}
